<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/5/9
 * Time: 9:19
 */

namespace zhtfrontend\controllers;

use common\models\datas\IsuserInfo;
use doumiaoduo\buildform\BuildForm;
use yii\widgets\ActiveForm;
use zhtfrontend\components\bases\BaseController;
use common\components\extenders\AjaxObject;
use common\components\helpers\Fun;
use zhtfrontend\models\datas\Coupons;
use yii\web\NotFoundHttpException;
use yii\web\Response;
use yii\web\BadRequestHttpException;
use yii\data\Pagination;
use yii\helpers\Json;
use zhtfrontend\models\datas\CouponsCode;

class CouponscodeController extends BaseController
{


    // public $layout='@app/views/layouts/iframe.php';

    /*
     * 优惠券领取列表
     * 2017-5-9
     * */
    public function actionIndex()
    {
        $param['searchData'] = \Yii::$app->request->get();
        $pageSize = isset($param['pageSize']) ? $param['pageSize'] : 12;

        $couponscode = CouponsCode::find()->orderBy('id DESC');
        if (!empty($param['searchData'])) {
            $search_data = array_filter($param['searchData']);
            if (!empty($search_data['coupons_id'])) {
                $couponscode->andWhere(['coupons_id' => $search_data['coupons_id']]);
            }
            if (!empty($search_data['salesman_id'])) {
                $couponscode->andWhere(['salesman_id' => $search_data['salesman_id']]);
            }
            if (isset($search_data['status']) && $search_data['status'] != null) {
                $couponscode->andWhere(['status' => $search_data['status']]);
            }
            if (isset($search_data['is_use']) && $search_data['is_use'] != null) {
                $couponscode->andWhere(['is_use' => $search_data['is_use']]);
            }
        }
        $pages = new Pagination(['totalCount' => $couponscode->count(), 'pageSize' => $pageSize]);
        isset($param['page']) ? $pages->page = $param['page'] - 1 : 0;
        $couponscode = $couponscode->offset($pages->offset)->limit($pages->limit)->all();
        $array = Fun::asArray($couponscode, ['coupons_name', 'invalid_time']);

        $salesman_id = CouponsCode::find()->select('salesman_id')->orderBy('salesman_id')->asArray()->all();
        $salesman = [];
        $salesman['null'] = '请选择';
        foreach ($salesman_id as $val) {
            $salesman_name = IsuserInfo::find()->select('contact')->where(['id' => $val])->asArray()->one();
            $salesman[$val['salesman_id']] = $salesman_name['contact'];
        }
        return $this->render('index', ['salesman' => $salesman, 'data' => $array, 'pages' => $pages]);
    }

    /*
     * 添加优惠券领取记录
     * 2017-5-8
     * */
    public function actionCreate()
    {
        $this->layout = false;
        $site_id = Fun::getSiteId();
        $model = new CouponsCode();
        $form = new BuildForm('@app/components/forms/couponcodeForm.php');
        $form->loadModel(['couponscode' => $model]);
        $form->loadDefaultValues();
        $coupons_id = [];
        $coupons = Coupons::find()->select('id,name,quantity,issue_qty')->where(['>=', 'end_time', time()])->all();
        foreach ($coupons as $v) {
            if (($v->quantity - $v->issue_qty) > 0)
                $coupons_id[$v['id']] = $v['name'] . ' (' . ($v->quantity - $v->issue_qty) . '张)';
        }

        $form->setData('couponscode', 'coupons_id','data', $coupons_id);
        //领券人id
        $salesman_id = [];
        $salesman = IsuserInfo::find()->select('id,contact')->where(['site_id' => $site_id, 'operation_type' => ['all', 'coupon']])->asArray()->all();
        foreach ($salesman as $v) {
            $salesman_id[$v['id']] = $v['contact'];
        }
        $form->setData('couponscode', 'salesman_id','data', $salesman_id);

        //ajax验证
        if (\Yii::$app->request->isAjax && \Yii::$app->request->post('ajax') == 'couponsCode-form' && $model->load(\Yii::$app->request->post())) {
            \Yii::$app->response->format = Response::FORMAT_JSON;
            return ActiveForm::validate($model);
        }
        //生成随机不重复的券码
        if ($model->load(\Yii::$app->request->post()) && $model->validate()) {

            $arr = $this->DuplicateCheck($model->number);
            $insert_arr = [];
            foreach ($arr as $k => $v) {
                $insert_arr[$k]['coupons_id'] = $model->coupons_id;
                $insert_arr[$k]['code'] = $v;
                $insert_arr[$k]['salesman_id'] = $model->salesman_id;
                $insert_arr[$k]['create_at'] = time();
                $insert_arr[$k]['user_id'] = \Yii::$app->user->id;
            }
            $res = Fun::getSiteDb()->createCommand()->batchInsert('{{%coupons_code}}', ['coupons_id', 'code', 'salesman_id', 'create_at', 'user_id'], $insert_arr)->execute();
            if ($res) {
                $couponsModel = Coupons::findOne($model->coupons_id);
                $couponsModel->issue_qty += $model->number;
                $couponsModel->save(false);
                return $this->redirectMessage('添加成功', Fun::url(['couponscode/index']));
            }
        }

        return $this->render('create', ['form' => $form->render()]);
    }

    /*
     * 随机生成字符串
     * length 字符串长度
     * 2017-5-9
     * */
    function getRandChar($length)
    {
        $str = null;
        $strPol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
        $max = strlen($strPol) - 1;

        for ($i = 0; $i < $length; $i++) {
            $str .= $strPol[rand(0, $max)];//rand($min,$max)生成介于min和max两个数之间的一个随机整数
        }

        return $str;
    }

    /*
     * 生成code并检查code是否重复
     * 2017-5-9
     * */

    function DuplicateCheck($number)
    {
        $numberArr = [];
        do {
            $code = $this->getRandChar(6);
            $codes = CouponsCode::find()->where(['code' => $code])->one();
            if ($codes == null && !in_array($code, $numberArr)) {
                $numberArr[] = $code;
            }
        } while (count($numberArr) < $number);

        return $numberArr;
    }
}